package com.hks360.car_treasure.internet.net_encrypt;


import android.util.Base64;

import java.net.URLEncoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

/**
 * Created by rwq on 2016/4/21.
 */

/**
 * 　　* <精简版DES加密>
 * <p>
 * 　　* @author 王乾州
 * <p>
 */

public class Des{
    private static final String DES = "DES";
    private static final String IV = "97536841";
    private static final String Key = "20160421";
    public static String encrypt(String datasource) {
        try {
            DESKeySpec desKey = new DESKeySpec(Key.getBytes());
            //创建一个密匙工厂，然后用它把DESKeySpec转换成
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
            SecretKey securekey = keyFactory.generateSecret(desKey);
            //Cipher对象实际完成加密操作
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            //用密匙初始化Cipher对象
            IvParameterSpec spec = new IvParameterSpec(IV.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, securekey, spec);
            //现在，获取数据并加密
            //正式执行加密操作

            return  URLEncoder.encode(new String(Base64.encode(cipher.doFinal(datasource.getBytes("UTF-8")), Base64.DEFAULT)),"UTF-8");
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     *
     * @param src      byte[]
     * @return byte[]
     * @throws Exception
     */
    public static byte[] decrypt(byte[] src) throws Exception {
        // 创建一个DESKeySpec对象
        DESKeySpec desKey = new DESKeySpec(Key.getBytes());
        // 创建一个密匙工厂
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        // 将DESKeySpec对象转换成SecretKey对象
        SecretKey securekey = keyFactory.generateSecret(desKey);
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        // 用密匙初始化Cipher对象
        IvParameterSpec spec = new IvParameterSpec(IV.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, securekey, spec);
        // 真正开始解密操作
        return cipher.doFinal(src);
    }
}